package com.group01.community.controller;

import cn.hutool.core.util.DesensitizedUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.group01.community.entity.SysUser;
import com.group01.community.entity.vo.SysUserInfoVo;
import com.group01.community.service.SysPostService;
import com.group01.community.service.SysUserPostService;
import com.group01.community.service.SysUserService;
import com.group01.community.utils.ResponseResult;
import com.group01.community.utils.StringUtils;
import com.group01.community.utils.UploadFileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author guoyuan
 * @since 2025-05-01
 */

@Api(tags = "用户信息")
@RestController
@RequestMapping("/sysUser")
public class SysUserController {
    public static final String DIR = "http://192.168.110.250/";
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysPostService sysPostService;

    @Resource
    private SysUserPostService sysUserPostService;

    @Autowired
    private FastFileStorageClient client;

    @Resource
    private UploadFileUtil uploadFileUtil;

    @ApiOperation("根据用户id查询角色")
    @GetMapping("/{userId}")
    public ResponseResult<SysUser> selectRoleByUserId(@PathVariable Long userId) {
        return ResponseResult.ok(sysUserService.selectRoleByUserId(userId));
    }

    @ApiOperation("分页查询用户")
    @GetMapping("/page")
    public ResponseResult<IPage<SysUserInfoVo>> selectUserPage(Long current, Long size, SysUser user) {
        return ResponseResult.ok(sysUserService.selectUserPage(current, size, user));
    }

    @ApiOperation("批量删除")
    @DeleteMapping("/{userIds}")
    public ResponseResult<String> deleteBatch(@PathVariable Long[] userIds) {
        sysUserService.removeByIds(Arrays.asList(userIds));
        return ResponseResult.ok("删除成功");
    }


    public static void main(String[] args) {
        String encode = new BCryptPasswordEncoder().encode("123456");
        System.out.println(encode);
    }

    @ApiOperation("用户新增")
    @PostMapping("/add")
    public ResponseResult<String> add(@RequestBody SysUser sysUser) {
        //密码加密
        sysUser.setPassword(new BCryptPasswordEncoder().encode(sysUser.getPassword()));
        sysUserService.save(sysUser);

        if  (sysUser.getRoleIds() != null && sysUser.getRoleIds().size() > 0) {
            sysUserService.updateUserRole(sysUser, "add");
        }

        if (sysUser.getPost() != null){
            sysUserPostService.handleUserPost(sysUser.getUserId(), sysUser.getPost(), "add");
        }

        return ResponseResult.ok("添加成功");
    }

    @ApiOperation("用户修改")
    @PostMapping("/update")
    public ResponseResult<String> update(@RequestBody SysUser sysUser) {
        if (sysUser.getUserId() == null){
            throw new RuntimeException("用户id不能为空");
        }

        LambdaUpdateWrapper<SysUser> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(SysUser::getUserId, sysUser.getUserId());
        lambdaUpdateWrapper.set(StringUtils.isNotEmpty(sysUser.getNickName()), SysUser::getNickName, sysUser.getNickName());
        lambdaUpdateWrapper.set(StringUtils.isNotEmpty(sysUser.getSex()), SysUser::getSex, sysUser.getSex());
        lambdaUpdateWrapper.set(sysUser.getDeptId() != null, SysUser::getDeptId, sysUser.getDeptId());
        lambdaUpdateWrapper.set(StringUtils.isNotEmpty(sysUser.getPhonenumber()), SysUser::getPhonenumber, sysUser.getPhonenumber());
        lambdaUpdateWrapper.set(StringUtils.isNotEmpty(sysUser.getEmail()), SysUser::getEmail, sysUser.getEmail());
        lambdaUpdateWrapper.set(StringUtils.isNotEmpty(sysUser.getStatus()), SysUser::getStatus, sysUser.getStatus());
        lambdaUpdateWrapper.set(StringUtils.isNotEmpty(sysUser.getRemark()), SysUser::getRemark, sysUser.getRemark());

        sysUserService.update(lambdaUpdateWrapper);

        sysUserService.updateUserRole(sysUser, "update");

        sysUserPostService.handleUserPost(sysUser.getUserId(), sysUser.getPost(), "update");

        return ResponseResult.ok("修改成功");
    }

    @ApiOperation("导入")
    @PostMapping("/import")
    public ResponseResult<String> importUser(MultipartFile file) throws IOException {
        List<SysUser> users = new ArrayList<>();
        EasyExcel.read(file.getInputStream(), SysUser.class, new PageReadListener<SysUser>(users::addAll)).sheet().doRead();
        sysUserService.insertBatch(users);
        return ResponseResult.ok("ok");
    }

    @ApiOperation("下载模板")
    @GetMapping("/downloadTemp")
    public ResponseResult<String> downloadTemp(HttpServletResponse resp) {
        try {
            List<SysUser> sysUserList = new ArrayList<>();
            //文件名
            String fileName = "user_template_" + System.currentTimeMillis();
            //设置下载信息
            resp.setContentType("application/vnd.ms-excel");
            resp.setCharacterEncoding("utf-8");
            resp.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //调用方法进行写操作
            EasyExcel.write(resp.getOutputStream(), SysUser.class)
                    .sheet("用户模板")
                    .registerWriteHandler(new SimpleColumnWidthStyleStrategy(15))
                    .doWrite(sysUserList);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseResult.ok("ok");
    }

    @ApiOperation("导出")
    @GetMapping("/export")
    public ResponseResult<String> export(HttpServletResponse resp) {
        try {
            List<SysUser> sysUserList = sysUserService.list();
            //文件名
            String fileName = UUID.randomUUID().toString();
            fileName = fileName.substring(0, fileName.indexOf("-"));
            //设置下载信息
            resp.setContentType("application/vnd.ms-excel");
            resp.setCharacterEncoding("utf-8");
            resp.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //调用方法进行写操作
            EasyExcel.write(resp.getOutputStream(), SysUser.class)
                    .sheet("用户数据信息")
                    .registerWriteHandler(new SimpleColumnWidthStyleStrategy(15))
                    .doWrite(sysUserList);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseResult.ok("ok");
    }

    @ApiOperation("根据用户名查询用户个人信息（岗位+部门+角色）")
    @GetMapping("/info/{userName}")
    public ResponseResult<SysUserInfoVo> getUserInfoByName(@PathVariable String userName) {
        SysUserInfoVo userInfo = sysUserService.getUserInfoByUserName(userName);
        //对用户手机号进行加密
        userInfo.setPhonenumber(DesensitizedUtil.mobilePhone(userInfo.getPhonenumber()));
        return ResponseResult.ok(userInfo);
    }

    @ApiOperation("修改个人信息")
    @PutMapping("/user")
    public ResponseResult<String> updateUserInfo(@RequestBody SysUser sysUser) {
        System.out.println(sysUser);
        //判断手机号是否有更改
        String c = String.valueOf(sysUser.getPhonenumber().charAt(4));
        if (c.equals("*")) {
            sysUser.setPhonenumber(null);
        }
        //判断密码是否更改
        SysUser user = sysUserService.getById(sysUser.getUserId());
        boolean b = user.getPassword().equals(sysUser.getPassword());
        if (b) {
            //不更改
            sysUser.setPassword(null);
        } else {
            //密码加密
            sysUser.setPassword(new BCryptPasswordEncoder().encode(sysUser.getPassword()));
        }
        sysUserService.updateUserInfo(sysUser);
        return ResponseResult.ok("ok");

    }

    @ApiOperation("修改头像")
    @PutMapping("/avatar")
    public ResponseResult<String> updateAvatar(@RequestBody SysUser sysUser) {
        sysUserService.updateById(sysUser);
        return ResponseResult.ok("ok");

    }

    @ApiOperation("验证个人密码")
    @PostMapping("/password")
    public ResponseResult<String> updatePassword(@RequestBody SysUser sysUser) {
        System.out.println(sysUser);
        SysUser user = sysUserService.getById(sysUser.getUserId());
        boolean b = new BCryptPasswordEncoder().matches(sysUser.getPassword(), user.getPassword());
        if (b) {
            return ResponseResult.ok("ok");
        } else {
            return ResponseResult.ok("error");
        }

    }

    @ApiOperation("上传")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ResponseEntity<String> upload(MultipartFile file) throws IOException {
        ////获得后缀名
        //String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        ////上传
        //StorePath storePath = client.uploadFile(file.getInputStream(), file.getSize(), extension, null);
        //DIR + storePath.getFullPath()

        ResponseResult<String> result = uploadFileUtil.uploadFile(file, "");

        //sysUserService.update(new UpdateWrapper<SysUser>().set("avatar", result.getData()));

        return ResponseEntity.ok(result.getData());
    }
    @ApiOperation("重置密码")
    @PutMapping("/updatePassword")
    public ResponseResult<String> updatePassword(@RequestBody String password) {
        sysUserService.updatePassword(password);
        return ResponseResult.ok("修改成功");
    }
}

